package com.bodgittandscarper.broker.client;

import static java.util.logging.Level.INFO;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import suncertify.db.Data;
import suncertify.db.RecordNotFoundException;

import com.bodgittandscarper.broker.types.DatabaseSchema;
import com.bodgittandscarper.broker.types.Record;
import com.bodgittandscarper.broker.types.TypeFactory;

/**
 * Implementation class of the BrokerClient interface for remote objects. 
 * This class is instantiated by the {@link com.bodgittandscarper.broker.server.Server} 
 * class and registered with the RMI registry. 
 * 
 * @author Morten Rummelhoff
 *
 */
public class BrokerClientImpl implements BrokerClient {

	private Data data;

	Logger log = Logger.getLogger(getClass().getName());

	public BrokerClientImpl(Data data) {
		this.data = data;	
	}

	@Override
	public DatabaseSchema getDatabaseSchema() {
		return	data.getDatabaseSchema();
	}

	@Override
	public Record[] findRecords(String[] criteria) throws RecordNotFoundException {
		int[] recNumbers = new int[0];
		List<Record> recordsList = null;

		recNumbers = data.find(criteria);

		if (log.isLoggable(INFO))
			log.log(INFO, "Found RecordNumbers: " + recNumbers.length);

		if (recNumbers.length > 0) {
			recordsList = new ArrayList<Record>();

			for (int recNo : recNumbers) {
				Record record = TypeFactory.getInstance().
				createRecordMod(recNo, true, data.isLocked(recNo), data.read(recNo));
				recordsList.add(record);
			}

		}

		return (Record[]) recordsList.toArray(new Record[recordsList.size()]);
	}

	@Override
	public void lockRecord(int recNo) throws RecordNotFoundException {
		data.lock(recNo);
	}

	@Override
	public void unlockRecord(int recNo) throws RecordNotFoundException {
		data.unlock(recNo);
	}

	@Override
	public void updateRecord(int recNo, String[] recordData) throws RecordNotFoundException {
		data.update(recNo, recordData);
	}

}
